<?php

namespace Base;

class Pagination
{
    public static function paginate($collectItem): string
    {
        $html = '';
        if ($collectItem->hasPages()) {
            $html .= '<ul class="pagination">';
            if ($collectItem->onFirstPage()) {
                $html .= '<li class="disabled"><span>&laquo;</span></li>';
            } else {
                $html .= '<li><a href="'.$collectItem->previousPageUrl().'" rel="prev">&laquo;</a></li>';
            }

            $element = $collectItem->linkCollection();
            foreach ($element as $item) {
                if ($item['label'] === 'Previous' || $item['label'] === 'Next') continue;
                if ($item['label'] == $collectItem->currentPage()) {
                    $html .= '<li class="active"><span>'.$item['label'].'</span></li>';
                } elseif (empty($item['url'])) {
                    $html .= '<li class="disabled"><span>'.$item['label'].'</span></li>';
                } else {
                    $html .= '<li><a href="'.$item['url'].'">'.$item['label'].'</a></li>';
                }
            }

            if ($collectItem->hasMorePages()) {
                $html .= '<li><a href="'.$collectItem->nextPageUrl().'" rel="next">&raquo;</a></li>';
            } else {
                $html .= '<li class="disabled"><span>&raquo;</span></li>';
            }
            $html .= '</ul>';
        }

        return $html;
    }

    public static function handleUrlQuery($url)
    {
        $urlInfo = parse_url($url);
        if (!isset($urlInfo['query'])) {
            return $url;
        }
        $query = explode('&', $urlInfo['query']);
        foreach ($query as $key => $item) {
            $params = explode('=', $item);
            if ($params[0] === 'p') {
                unset($query[$key]);
            }
        }
        $urlQuery = implode('&', $query);

        return (str_replace($urlInfo['query'], '', $url)) . $urlQuery;
    }
}